<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输角色名称" clearable v-model="name" @clear="searchRole">
                        <el-button slot="append" icon="el-icon-search" @click="addRole"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>

            <el-table :data="roleList" border style="width: 100%">
                <el-table-column prop="id" label="角色ID"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="showEditDialog(scope.row)">修改</el-button>
                        <el-button type="danger" @click="removeRoleById(scope.row.id)">删除</el-button>
                        <el-button type="warning" @click="openGrantDialog(scope.row)">授权</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 15, 20, 30, 40, 50, 60]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!-- 新增角色对话框 -->
        <el-dialog title="新增角色" :visible.sync="addDialogVisible">
            <el-form :model="addRoleForm" ref="addRoleForm" :rules="rules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole()">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改角色对话框 -->

        <!-- 角色授权对话框 -->
        <el-dialog title="角色授权" :visible.sync="grantDialogVisible" :before-close="handleClose">
            <el-tree
                :data="permissionList"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="tree"
                highlight-current
                :props="defaultProps"
                :check-strictly="myStrict"
                :default-checked-keys="defaultChecked">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="grantPermissionClose">取 消</el-button>
                <el-button type="primary" @click="doGrantPermission">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {Message} from "element-ui";

export default {
    name: "RoleView",
    data() {
        let checkRoleName = (rule, value, callback) => {
            // 发送请求到后端，去验证角色名是否存在
            let url = "/api/role/checkRoleName/" + value
            this.$axios.get(url).then(res => {
                if (res.data.code == 200) {
                    // 可以使用
                    callback();
                } else {
                    this.getAllRole();
                    callback(new Error(res.data.message));
                }
            })
        };

        return {
            name: "",
            roleList: [],
            pageNum: 1,
            pageSize: 5,
            total: 0,
            rules: {
                roleName: [
                    {required: true, message: "请输入角色名称", trigger: "blur"},
                    {mix: 2, max: 20, message: "角色名长度为2-20", trigger: "blur"},
                    {validator: checkRoleName, trigger: "blur"}
                ]
            },
            // 新增角色需要的相关数据 ----------------------------------------------
            addDialogVisible: false,
            addRoleForm: {
                roleName: ""
            },
            // 授权需要的相关数据 --------------------------------------------------
            grantDialogVisible: false,    // 授权对话框是否显示
            permissionList: [],           // 所有的权限
            defaultProps: {
                label: 'name',
                children: 'children'
            },
            myStrict: false,              // 是否使用严格模式(严格模式：回显数据时,勾选父级,不会全部选中子级)
            defaultChecked: [],           // 默认勾选中的权限
            roleId: ''                    // 是要授权的角色id
        }
    },
    methods: {
        getAllRole() {
            console.log("----- get all roles ------")
            this.$axios.get("/api/role/showAll", {
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                }
            }).then(res => {
                console.log("得到的所有角色信息：", res.data);
                if (res.data.code == 200) {
                    this.roleList = res.data.data.list;
                    this.pageNum = res.data.data.pageNum;
                    this.pageSize = res.data.data.pageSize;
                    this.total = res.data.data.total;
                }
            })
        },
        getAllPermission() {
            let url = "/api/getAllPermission";
            this.$axios.get(url).then(res => {

                if (res.data.code == 200) {
                    this.permissionList = res.data.data
                }
            })
        },
        showEditDialog() {

        },
        removeRoleById() {

        },
        openGrantDialog(row) {
            // 打开窗口，回显示数据，要勾选父级时不会选中所有的子级，所以需要严格模式
            this.myStrict = true;
            // 显示对话框
            this.grantDialogVisible = true;
            this.roleId = row.id;

            console.log("访问后端的角色id:" + this.roleId);

            let url = "/api/getPermissionById/" + this.roleId;
            this.$axios.get(url).then(res => {

                console.log("根据roleId得到的权限id:", res)

                if (res.data.code == 200) {

                    this.defaultChecked = res.data.data;
                    // 显示完数据之后，又不需要严格模式了。
                    this.myStrict = false;
                }
            })
        },
        searchRole() {

        },
        addRole() {
            // 添加角色
            this.$refs["addRoleForm"].validate((valid) => {
                if (valid) {
                    console.log("--- 验证通过 ---")

                } else {
                    return false;
                }
            });
        },
        //点击授权窗口的小叉叉关闭对话框
        handleClose() {
            this.grantPermissionClose();
            this.$refs.tree.setCheckedKeys([]);
        },
        // 关闭授权窗口
        grantPermissionClose() {
            this.grantDialogVisible = false;
            // this.defaultChecked = [];  //这么写无法取消勾选
            this.$refs.tree.setCheckedKeys([]);
        },
        // 确定授权
        doGrantPermission() {
            // 得到全选的id
            let checkedId = this.$refs.tree.getCheckedKeys();
            // 得到半选的id
            let halfCheckedId = this.$refs.tree.getHalfCheckedKeys();
            // 全选和半选的id都是我们需要的
            let permissionIds = checkedId.concat(halfCheckedId);

            //console.log(permissionIds);
            let url = "/api/grantPermissionByRoleId";

            let params = new URLSearchParams();
            params.append("roleId", this.roleId);
            params.append("ids", permissionIds);

            this.$axios.put(url, params)
                .then(res => {
                    if(res.data.code == 200){
                        this.$message({
                            type: "success",
                            message: res.data.message,
                            duration: 1000
                        })
                    }else {
                        Message({
                            type: "error",
                            message: res.data.message,
                            duration: 1000
                        })
                    }
                })
            // 完成之后，关闭对话框
            this.grantPermissionClose();
        },
        handleSizeChange(val) {
            console.log("改变的页大小是：" + val)
            this.pageSize = val;
            this.getAllRole();
        },
        handleCurrentChange(val) {
            console.log("改变的当前页是：" + val)
            this.pageNum = val;
            this.getAllRole();
        }
    },
    mounted() {
        this.getAllRole();
        this.getAllPermission();
    }
}
</script>

<style scoped>
</style>
